package com.dragon.backstage.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.dragon.backstage.domain.param.file.FileUploadParam;
import com.dragon.backstage.domain.vo.file.FileUploadVo;
import com.dragon.backstage.service.FileService;
import com.dragon.common.utils.AjaxResult;
import com.dragon.common.utils.time.DateTimePattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 文件模块服务实现类
 *
 * @author dragon
 * @version 1.0
 * @date 2024/8/9 16:21
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Value("${file.save-path}")
    private String fileSavePath;
    @Value("${file.visit-url}")
    private String fileVisitUrl;


    /**
     * 文件上传
     *
     * @param param 请求参数
     * @return 文件路径
     */
    @Override
    public AjaxResult<FileUploadVo> uploadFile(FileUploadParam param) {
        AjaxResult<Void> check = FileUploadParam.check(param);
        if (!check.getIsSuccessful()) {
            return AjaxResult.failed(check.getMessage());
        }

        String filePath = DateUtil.format(LocalDateTime.now(), DateTimePattern.UNSIGNED_DATE_PATTERN) + StrUtil.SLASH + UUID.randomUUID() + StrUtil.DOT + FileUtil.extName(param.getFile().getOriginalFilename());
        try {
            File uploadParentFile = new File(fileSavePath + DateUtil.format(LocalDateTime.now(), "yyyyMMdd"));
            if (!uploadParentFile.exists()) {
                boolean mkdirFlag = uploadParentFile.mkdirs();
                if (!mkdirFlag) {
                    return AjaxResult.failed("文件上传目录创建失败");
                }
            }

            File saveFile = new File(fileSavePath + filePath);
            param.getFile().transferTo(saveFile);
        } catch (IOException e) {
            log.error("文件模块-上传文件异常", e);
            return AjaxResult.failed("文件上传失败");
        }

        return AjaxResult.succeedWith(FileUploadVo
            .builder()
            .fileUrl("uploads" + StrUtil.SLASH + filePath)
            .fileFullUrl(fileVisitUrl + filePath)
            .build()
        );
    }

}
